from flask_restplus import Namespace, Resource
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from app.models import User
from flask import request, g, jsonify, current_app
from werkzeug.security import check_password_hash
from app.extensions import cache


api = Namespace('auth', description='登录认证')
auth = HTTPTokenAuth(scheme='Token')


@auth.verify_token
def verify_token(token):
    if cache.get(token) == 'token黑名单':
        return False
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token.encode('utf8'))
        g.data = data
        return True
    except:
        return False


@api.route('/<int:uid>/', '/')
class UserAPI(Resource):
    method_decorators = [auth.login_required]

    def get(self):
        user = User.query.filter_by(username=g.data['username']).first()
        user_list = []
        user_list.append({'name': user.name, 'username': user.username, 'age': user.age})
        return user_list[0]

    def put(self):
        user = User.query.filter_by(username=g.data['username']).first()
        user.name = request.form.get('name')
        print(user.name)
        user.age = request.form.get('age')
        return '修改成功'


@api.route('/login/')
class UserListAPI(Resource):
    def post(self):
        username = request.form.get('username')
        password = request.form.get('password')
        user = User.query.filter_by(username=username).first()
        if user:
            password_auth = check_password_hash(user.password, password)
            if password_auth:
                s = Serializer(current_app.config['SECRET_KEY'], expires_in=3600)
                token = s.dumps({'username': username})
                return jsonify({'access_token': token.decode('utf8')})
            return '密码有误，请核实'
        return '登录失败，请核实用户名'

    def delete(self):
        cache.set(request.headers['Authorization'][6:], 'token黑名单', timeout=3600)
